<?php
/**
 * EDM 统计并推送今日接收量和发送量
 *
 * @author kangpengfei
 *
 * is_old = 1 时
 *     goods_type = 1 表示购物车
 *     goods_type = 4 表示浏览记录
 * is_old = 2 时
 *     user_email_type = 1 表示购物车
 */

namespace app\controllers\crontab;

use Yii;
use yii\helpers\Html;
use yii\web\Controller;
use app\models\marketing\PushGroupLog;
use app\models\marketing\PushSendLog;
use app\models\marketing\SendReportLog;
use app\components\McsApi;

class EdmPushGroupLogController extends Controller 
{
	const STEP_BIGDATA = 1;  //推送环节-大数据
	const STEP_WEBSITE = 2;  //推送环节-网站
	const STEP_EDM = 3;  //推送环节-edm
	const MAIL_TYPE_CART = 1;  //邮件类型-购物车(接口定义,非系统定义)
	const MAIL_TYPE_VIEW = 2;  //邮件类型-浏览记录(接口定义,非系统定义)
	
	//推送环节可选项
	protected $stepArr = [
		self::STEP_BIGDATA,
		self::STEP_WEBSITE,
		self::STEP_EDM,
	];
	
	//邮件类型可选项(新增站点时,这里需要配置,有什么类型的数据则就要在对应类型下面的open_sites下面增加站点名称)
	protected $mailTypeArr = [
		self::MAIL_TYPE_CART => [
			"name" => "购物车邮件",
			"open_sites" => [
				"gearbest", "sammydress", "dresslily", "rosegal", "rosewholesale"
			],
		],
		self::MAIL_TYPE_VIEW => [
			"name" => "浏览记录邮件",
			"open_sites" => [
				"gearbest", "rosegal"
			],
		],
	];
	
	//接口地址和密钥
	protected $apiUrl = "";
	protected $apiKey = "";
	
	//推送接口配置信息
	protected $apiConfigArr = [
		"test" => [
			//"apiUrl" => "http://ems.com/marketing/api-push-group-log/index?module_name=marketing_email",
			"apiUrl" => "http://ems.com.a.s1cg.egomsl.com/marketing/api-push-group-log/index?module_name=marketing_email",
			"apiKey" => "G7d9Ed8JbvS9dfeo123ndOs22isdnrEcX",
		],
		"product" => [
			"apiUrl" => "http://ems.appinthestore.com/marketing/api-push-group-log/index?module_name=marketing_email",
			"apiKey" => "15c7a923e878bbce40c619e898ba1b34",
		],
	];
	
	//站点可选项(站点接入时需配置)
	protected $siteArr = [
		"sammydress",
		"gearbest",
		"rosewholesale",
		"rosegal",
		"zaful",
		"dresslily",
	];
	
	//站点名称 对应 站点Code(站点接入时需配置,参考web.marketing_email.php文件)
	protected $webCode = [
		"sammydress" => "S",
		"gearbest" => "GB",
		"rosewholesale" => "RW",
		"rosegal" => "RG",
		"zaful" => "Z",
		"dresslily" => "D",
	];
	
	//站点名称 对应 站点id
	protected $webIndex = [];
	
	//是否立即执行
	protected $atOnceRun = false;
	
	/**
	 * 初始化赋值
	 */
	public function init()
	{
		parent::init();
		
		//取出接口地址和密钥
		$this->apiUrl = $this->getApiUrl();
		$this->apiKey = $this->getApiKey();
		
		//取出配置文件中的站点id对应站点数据
		$webIndex = Yii::$app->params["sites"]["marketing_email"]["web_index"];
		$webIndex = array_flip($webIndex);
		$this->webIndex = $webIndex;
		
		//是否立即执行
		$get = Yii::$app->request->get();
		$this->atOnceRun = isset($get['at_once_run']) && $get['at_once_run'] == 'please' ? true : false;
	}
	
	/**
	 * 推送各站点今日的接收量
	 * [计划每隔10分钟统计并推送一次, 只有21点的时候才有效,也就是一天最多执行3次]
	 */
	public function actionPushReceiveNum()
	{
		header("content-type:text/html; charset=utf8");
		$currTime = Yii::$app->systime->time();
		$msg = "";
		
		//17:00 - 17:20 之间执行
		$currHour = Yii::$app->systime->date($currTime, "H");
		$currMin = Yii::$app->systime->date($currTime, "i");
		if ( ($currHour == 17 && $currMin <= 20) || $this->atOnceRun )
		{
			try
			{
				$urls = [];
				$dataArr = [];
				$result = [];
				foreach ($this->siteArr as $site)
				{
					$siteInfo = [
						"site_id" => $this->webIndex[$site],
						"site_name" => $site
					];
					$data = $this->countReceiveNum($siteInfo);  //按 [邮件类型=> 数量] 返回数据
					if ($data)
					{
						foreach ($data as $mailType => $total)
						{
							if (! in_array($site, $this->mailTypeArr[$mailType]["open_sites"]))
							{
								continue;
							}
							$arr = [
								"step" => self::STEP_EDM,
								"site_name" => $site,
								"origin_nums" => $total,
								"filter_nums" => 0,  //EDM环节 这里固定都是0
								"mail_type" => $mailType
							];
							$dataArr[] = $arr;
							$json = urlencode(json_encode($arr));
							$token = md5($this->apiKey . $json);
							$urls[] = [
								"url" => $this->apiUrl,
								"data" => [
									"token" => $token,
									"data" => $json
								]
							];
						}
					}
				}
				
				if ($urls)
				{
					$result = $this->multiRequest($urls);
				}
				
				var_dump($dataArr);
				var_dump($result);
			}
			catch (\Exception $e)
			{
				echo "#FILE: " . $e->getFile() . "<br/>" . "#LINE: " . $e->getLine() . "<br/>" . "#ERROR: " . $e->getMessage();
			}
		}
		else
		{
			$msg .= "#此定时任务只在17:00 - 17:20 之间执行.<br/>";
		}
		
		$end = Yii::$app->systime->time();
		$used = $end - $currTime;
		$msg .= "used: " . $used . "s";
		die($msg);
	}
	
	/**
	 * 统计各站点今日的发送量
	 */
	public function actionPushSendNum()
	{
		header("content-type:text/html; charset=utf8");
		$currTime = Yii::$app->systime->time();
		$msg = "";
		
		//17:00 - 17:20 之间执行
		$currHour = Yii::$app->systime->date($currTime, "H");
		$currMin = Yii::$app->systime->date($currTime, "i");
		if ( ($currHour == 17 && $currMin <= 20) || $this->atOnceRun )
		{
			try
			{
				$pushSendLogModel = new PushSendLog();
				$pushGroupLogModel = new PushGroupLog();
				$dataArr = [];
				$resultArr = [];
				foreach ($this->siteArr as $site)
				{
					$siteInfo = [
						"site_id" => $this->webIndex[$site],
						"site_code" => $this->webCode[$site],
						"site_name" => $site
					];
					$data = $this->countSendNum($siteInfo);  //按 [ 邮件类型=> [ 发送日期 => '', 接收日期 => '', 发送数量 => '' ] ] 返回数据
					if ($data)
					{
						foreach ($data as $key => $val)
						{
							if (empty($val["receive_date"]) || empty($val["send_date"]))
							{
								continue;
							}
							
							//保存数据
							$val["site_name"] = $site;
							$val["mail_type"] = $key;
							$val["site_id"] = $siteInfo["site_id"];
							$val["site_type"] = $this->getSiteType($siteInfo["site_id"]);
							$result = $pushSendLogModel->doSaveSendLog($val);
							$resultArr[$site][$key] = $result;
							
							/*
							//回写push_group_log表中receive_date = '今日' AND step=3时 filter_nums的值     $val["send_date"]表示今日
							$update = [
								"filter_nums" => $val["send_nums"],
								"update_time" => Yii::$app->systime->time()
							];
							$pushGroupLogModel->updateAll($update, "`receive_date` = '{$val["send_date"]}' AND `step` = 3 AND `site_name` = '{$site}' AND `mail_type` = {$key} ");
							*/
						}
					}
					$dataArr[$site] = $data;
				}
				
				var_dump($dataArr);
				var_dump($resultArr);
			}
			catch (\Exception $e)
			{
				echo "#FILE: " . $e->getFile() . "<br/>" . "#LINE: " . $e->getLine() . "<br/>" . "#ERROR: " . $e->getMessage();
			}
		}
		else
		{
			$msg .= "#此定时任务只在17:00 - 17:20 之间执行.<br/>";
		}
		
		$end = Yii::$app->systime->time();
		$used = $end - $currTime;
		$msg .= "used: " . $used . "s";
		die($msg);
	}
	
	/**
	 * 今日 生成报表内容
	 * [不同站发给不同的人]
	 */
	public function actionCreateReport()
	{
		header("content-type:text/html; charset=utf8");
		$currTime = Yii::$app->systime->time();
		$msg = "";
		
		//17:20 ~ 17:40 之间执行
		$currHour = Yii::$app->systime->date($currTime, "H");
		$currMin = Yii::$app->systime->date($currTime, "i");
		if ( ($currHour == 17 && $currMin > 20 && $currMin <= 40) || $this->atOnceRun )
		{
			try
			{
				$sendReportLogModel = new SendReportLog();
				
				$reportDate = Yii::$app->systime->date("", "Y-m-d");
				$resultArr = [];
				
				//按站点类型区分接收和发送报表
				$webType = Yii::$app->params["sites"]["marketing_email"]["web_type"];
				foreach ($webType as $type => $info)
				{
					//今日接收情况报表
					$receiveData = $this->getReceiveReportData($type);
					$receiveIdStr = join(",", $receiveData["receiveIdArr"]);
					$receiveHtml = $receiveData["receiveHtml"];
					$receiveSiteArr = $receiveData["siteNameArr"];
					
					//今日发送情况报表
					$sendData = $this->getSendReportData($type);
					$sendIdStr = join(",", $sendData["sendIdArr"]);
					$sendHtml = $sendData["sendHtml"];
					$sendSiteArr = $sendData["siteNameArr"];
					
					//合并接收和发送报表
					$reportHtml = $receiveHtml . "<br/><br/>" . $sendHtml;
					
					//站点简码集合,多个用逗号隔开
					$siteNameArr = array_merge($receiveSiteArr, $sendSiteArr);  //合并
					$siteNameArr = array_unique($siteNameArr);  //去重
					$siteCodeArr = $this->getSiteCode($siteNameArr);
					$siteCodeStr = join(",", $siteCodeArr);
					
					//入库
					$indata = [
						"report_date" => $reportDate,
						"receive_id_str" => $receiveIdStr,  //push_group_log表的id,多个用逗号隔开, 用于报表发送后回写is_report,report_time值
						"send_id_str" => $sendIdStr,  //push_send_log表的id,多个用逗号隔开, 用于报表发送后回写is_report,report_time值
						"site_type" => $type,
						"site_code_str" => $siteCodeStr,
						"send_data" => Html::encode($reportHtml),
					];
					$result = $sendReportLogModel->saveData($indata);
					$resultArr[] = $result;
				}
				
				var_dump($resultArr);
			}
			catch (\Exception $e)
			{
				echo "#FILE: " . $e->getFile() . "<br/>" . "#LINE: " . $e->getLine() . "<br/>" . "#ERROR: " . $e->getMessage();
			}
		}
		else
		{
			$msg .= "#此定时任务只在17:20 - 17:40 之间执行.<br/>";
		}
		
		$end = Yii::$app->systime->time();
		$used = $end - $currTime;
		$msg .= "used: " . $used . "s";
		die($msg);
	}
	
	/**
	 * 调用消息中心发送报表数据
	 */
	public function actionSendReport()
	{
		header("content-type:text/html; charset=utf8");
		$currTime = Yii::$app->systime->time();
		$total = 0;
		$success = 0;
		$msg = "";
		
		//邮件标题
		$titleArr = [
			'1' => "电子站[{sites}]-邮件数据统计报表-{date}",  //电子站[gb]-邮件数据统计报表-日期
			"2" => "服装站[{sites}]-邮件数据统计报表-{date}",  //服装站[s、rg]-邮件数据统计报表-日期
		];
		
		//17:40 ~ 20:00 之间执行
		$currHour = Yii::$app->systime->date($currTime, "H");
		$currMin = Yii::$app->systime->date($currTime, "i");
		$currHourMin = intval($currHour . $currMin);
		if ( ($currHourMin > 1740 && $currHourMin < 2000) || $this->atOnceRun )
		{
			try
			{
				$maxTime = $currTime + 40;
				
				$sendReportLogModel = new SendReportLog();
				$pushGroupLogModel = new PushGroupLog();
				$pushSendLogModel = new PushSendLog();
				$mcsApi = new McsApi();
				
				while(Yii::$app->systime->time() < $maxTime)
				{
					//获取一个待发送的报表 并锁定
					$report = $sendReportLogModel->getWaittingSendReportAndLock();
					if (! $report)
					{
						sleep(3);
						continue;
					}
					
					//调用消息中心接口
					$title = isset($titleArr[$report["site_type"]]) ? $titleArr[$report["site_type"]] : "邮件数据统计-{date}";
					$sites = str_replace(",", "、", $report["site_code_str"]);  //站点简码(可能多个)
					$placeFrom = ["{sites}", "{date}"];
					$placeTo = [$sites, $report["report_date"]];
					$title = str_replace($placeFrom, $placeTo, $title);
					$param = [
						"channel" => "email",  //email支持自定义发送人名称,  cheetahmail不支持
						"to" => $this->getReceiver($report["site_type"]),
						"title" => $title,
						"content" => Html::decode($report["send_data"]),
						"from_name" => "EMP邮件管理平台",  //发件人名称
						"from" => "emp-system@globalegrow.com",  //这个是假邮箱,可以随便填写,只要符合邮箱格式
					];
					$result = $mcsApi->send($param);
					$sendStatus = 3;  //0待发送, 1发送中, 2发送成功, 3发送失败
					$sendTime = Yii::$app->systime->time();
					if ($result["httpCode"] == 200)
					{
						$backData = json_decode($result["result"], true);
						if (isset($backData["code"]) && $backData["code"] == 0)
						{
							//发送成功
							$sendStatus = 2;
							
							//回写push_group_log表和push_send_log表的is_report, report_time字段
							$update = [
								"is_report" => 1,
								"report_time" => $sendTime
							];
							if (! empty($report["receive_id_str"]))
							{
								$pushGroupLogModel->updateAll($update, " `id` IN({$report["receive_id_str"]}) ");
							}
							if (! empty($report["send_id_str"]))
							{
								$pushSendLogModel->updateAll($update, " `id` IN({$report["send_id_str"]}) ");
							}
							//end
						}
					}
					
					//修改本条数据的状态
					$update = [
						"id" => $report["id"],
						"send_time" => $sendTime,
						"send_to" => $param["to"],
						"send_status" => $sendStatus,
						"back_data" => $result["result"],
						"http_code" => $result["httpCode"]
					];
					$status = $sendReportLogModel->releasedSendReport($update);
					if ($status)
					{
						$success++;
					}
					$total++;
				}
			}
			catch (\Exception $e)
			{
				echo "#FILE: " . $e->getFile() . "<br/>" . "#LINE: " . $e->getLine() . "<br/>" . "#ERROR: " . $e->getMessage();
			}
		}
		else
		{
			$msg .= "#此定时任务只在17:40 - 23:00 之间执行.<br/>";
		}
		
		$end = Yii::$app->systime->time();
		$used = $end - $currTime;
		$msg .= "used: " . $used . "s" .  ", total: " . $total . ", success: " . $success;
		die($msg);
	}
	
	/**
	 * 根据站点取站点简码
	 */
	protected function getSiteCode($siteArr = [])
	{
		$siteCodeArr = [];
		
		try
		{
			if ($siteArr)
			{
				$webConfig = Yii::$app->params["sites"]["marketing_email"]["web_config"];
				foreach ($siteArr as $site)
				{
					$siteCodeArr[] = isset($webConfig[$site]["brief_code"]) && ! empty($webConfig[$site]["brief_code"]) ? $webConfig[$site]["brief_code"] : $site;
				}
			}
		}
		catch (\Exception $e)
		{
			echo "#FILE: " . $e->getFile() . "<br/>" . "#LINE: " . $e->getLine() . "<br/>" . "#ERROR: " . $e->getMessage();
		}
		
		return $siteCodeArr;
	}
	
	/**
	 * 取接收者邮件
	 */
	protected function getReceiver($siteType = 0)
	{
		$receiver = "";
		if ($siteType)
		{
			$webType = Yii::$app->params["sites"]["marketing_email"]["web_type"];
			$receiverArr = isset($webType[$siteType]["receiver"]) ? $webType[$siteType]["receiver"] : [];
			$receiver = join(",", $receiverArr);
		}
		return $receiver;
	}
	
	/**
	 * 今日接收情况报表
	 */
	protected function getReceiveReportData($siteType)
	{
		$pushGroupLogModel = new PushGroupLog();
		
		$receiveDate = Yii::$app->systime->date("", "Y-m-d");
		//$receiveDate = '2017-11-17';
		$receiveHtml = "";
		$receiveData = [];
		$siteNameArr = [];  //站点
		
		$receiveIdArr = [];
		$tempReceiveData = $pushGroupLogModel->find()->where(" `site_type` = {$siteType} AND `receive_date` = '{$receiveDate}' AND `is_report` = 0 ")->asArray()->all();
		if ($tempReceiveData)
		{
			$receiveIdArr = array_column($tempReceiveData, "id");
			foreach ($tempReceiveData as $key => $val)
			{
				$receiveData[$val["site_name"]][$val["mail_type"]][$val["step"]] = $val;
			}
		}
		
		//组合数据
		$html = "<style> table{width:800px; border-right:1px solid #000; border-bottom:1px solid #000;} table tr td{height:25px; line-height:25px; text-align:center; border-top:1px solid #000; border-left:1px solid #000;}</style>";
		$html .= "<p>今日接收数据表</p>";
		$html .= "<table cellpadding='0' cellspacing='0'>";
		$html .= "<tr>";
		$html .= " <td rowspan='2'>日期</td>";
		$html .= " <td rowspan='2'>站点名称</td>";
		$html .= " <td rowspan='2'>邮件类型</td>";
		$html .= " <td colspan='2' align='center'>大数据</td>";
		$html .= " <td colspan='2' align='center'>网站</td>";
		$html .= " <td align='center'>EMP</td>";
		$html .= "</tr>";
		$html .= "<tr>";
		$html .= " <td>原始数据</td>";
		$html .= " <td>实推数据</td>";
		$html .= " <td>原始数据</td>";
		$html .= " <td>实推数据</td>";
		$html .= " <td>原始数据</td>";
		$html .= "</tr>";
		if ($receiveData)
		{
			foreach ($receiveData as $site => $value)
			{
				foreach ($this->mailTypeArr as $mailType => $val)
				{
					//只有站点开启了对应类型的数据时才统计
					if (! in_array($site, $val["open_sites"]))
					{
						continue;
					}
					$siteNameArr[] = $site;  //站点
					
					$html .= "<tr>";
					$html .= "<td>{$receiveDate}</td>";
					$html .= "<td>{$site}</td>";
					$html .= "<td>{$val["name"]}</td>";
					
					//大数据
					$originNums = isset($receiveData[$site][$mailType][self::STEP_BIGDATA]) ? $receiveData[$site][$mailType][self::STEP_BIGDATA]["origin_nums"] : 0;
					$filterNums = isset($receiveData[$site][$mailType][self::STEP_BIGDATA]) ? $receiveData[$site][$mailType][self::STEP_BIGDATA]["filter_nums"] : 0;
					if ($mailType == self::MAIL_TYPE_CART)
					{
						$html .= "<td>-</td>";
						$html .= "<td>-</td>";
					}
					else
					{
						$html .= "<td>{$originNums}</td>";
						$html .= "<td>{$filterNums}</td>";
					}
					
					//网站
					$originNums = isset($receiveData[$site][$mailType][self::STEP_WEBSITE]) ? $receiveData[$site][$mailType][self::STEP_WEBSITE]["origin_nums"] : 0;
					$filterNums = isset($receiveData[$site][$mailType][self::STEP_WEBSITE]) ? $receiveData[$site][$mailType][self::STEP_WEBSITE]["filter_nums"] : 0;
					$html .= "<td>{$originNums}</td>";
					$html .= "<td>{$filterNums}</td>";
					
					//EMP
					$originNums = isset($receiveData[$site][$mailType][self::STEP_EDM]) ? $receiveData[$site][$mailType][self::STEP_EDM]["origin_nums"] : 0;
					$filterNums = isset($receiveData[$site][$mailType][self::STEP_EDM]) ? $receiveData[$site][$mailType][self::STEP_EDM]["filter_nums"] : 0;
					$html .= "<td>{$originNums}</td>";
					
					$html .= "</tr>";
				}
			}
		}
		else
		{
			$html .= "<tr><td colspan='8'>暂无数据</td></tr>";
		}
		$html .= "</table>";
		$receiveHtml = $html;
		
		$data = [
			"receiveIdArr" => $receiveIdArr,
			"receiveHtml" => $receiveHtml,
			"siteNameArr" => $siteNameArr,
		];
		
		return $data;
	}
	
	/**
	 * 今日发送情况报表
	 */
	protected function getSendReportData($siteType)
	{
		$pushSendLogModel = new PushSendLog();
		
		$sendDate = Yii::$app->systime->date("", "Y-m-d");
		//$sendDate = '2017-11-17';
		$sendHtml = "";
		$siteNameArr = [];  //站点
		
		$sendIdArr = [];
		
		$tempSendData = $pushSendLogModel->find()->where(" `site_type` = {$siteType} AND `send_date` = '{$sendDate}' AND `is_report` = 0 ")->asArray()->all();

		//组合数据
		$html = "<style> table{width:800px; border-right:1px solid #000; border-bottom:1px solid #000;} table tr td{height:25px; line-height:25px; text-align:center; border-top:1px solid #000; border-left:1px solid #000;}</style>";
		$html .= "<p>今日发送数据表</p>";
		$html .= "<table cellpadding='0' cellspacing='0'>";
		$html .= "<tr>";
		$html .= " <td rowspan='2'>邮件发送日期</td>";
		$html .= " <td rowspan='2'>站点名称</td>";
		$html .= " <td rowspan='2'>邮件类型</td>";
		$html .= " <td rowspan='2'>数据来源日期</td>";
		$html .= " <td colspan='2' align='center'>EMP</td>";
		$html .= " <td colspan='2' align='center'>网站</td>";
		$html .= " <td colspan='2' align='center'>大数据</td>";
		$html .= "</tr>";
		$html .= "<tr>";
		$html .= " <td>实发数据</td>";
		$html .= " <td>原始数据</td>";
		$html .= " <td>实推数据</td>";
		$html .= " <td>原始数据</td>";
		$html .= " <td>实推数据</td>";
		$html .= " <td>原始数据</td>";
		$html .= "</tr>";
		if ($tempSendData)
		{
			$sendIdArr = array_column($tempSendData, "id");
			foreach ($tempSendData as $key => $val)
			{
				$site = $val["site_name"];
				//只有站点开启了对应类型的数据时才统计
				if (! in_array($site, $this->mailTypeArr[$val["mail_type"]]["open_sites"]))
				{
					continue;
				}
				
				$siteNameArr[] = $site;  //站点
				
				$receiveDate = $val["receive_date"];
				$html .= "<tr>";
				$html .= "<td>{$sendDate}</td>";
				$html .= "<td>{$site}</td>";
				$html .= "<td>{$this->mailTypeArr[$val["mail_type"]]["name"]}</td>";
				$html .= "<td>{$receiveDate}</td>";
				$html .= "<td>{$val["send_nums"]}</td>";
				
				//获取接收数据
				$param = [
					"receive_date" => $receiveDate,
					"site_name" => $site,
					"mail_type" => $val["mail_type"]
				];
				$receiveData = $this->getReceiveData($param);
				
				//EMP
				$originNums = $receiveData[self::STEP_EDM]["origin_nums"];
				$html .= "<td>{$originNums}</td>";
				
				//网站
				$filterNums = $receiveData[self::STEP_WEBSITE]["filter_nums"];
				$originNums = $receiveData[self::STEP_WEBSITE]["origin_nums"];
				$html .= "<td>{$filterNums}</td>";
				$html .= "<td>{$originNums}</td>";
				
				//大数据
				$filterNums = $receiveData[self::STEP_BIGDATA]["filter_nums"];
				$originNums = $receiveData[self::STEP_BIGDATA]["origin_nums"];
				if ($val["mail_type"] == self::MAIL_TYPE_CART)
				{
					$html .= "<td>-</td>";
					$html .= "<td>-</td>";
				}
				else
				{
					$html .= "<td>{$filterNums}</td>";
					$html .= "<td>{$originNums}</td>";
				}
				
				$html .= "</tr>";
			}
		}
		else
		{
			$html .= "<tr><td colspan='10'>暂无数据</td></tr>";
		}
		$html .= "</table>";
		
		$sendHtml = $html;
		
		$data = [
			"sendIdArr" => $sendIdArr,
			"sendHtml" => $sendHtml,
			"siteNameArr" => $siteNameArr,
		];
		
		return $data;
	}
	
	/**
	 * 获取接收数据
	 */
	protected function getReceiveData($param = [])
	{
		$data = [
			self::STEP_EDM => ["origin_nums" => 0, "filter_nums" => 0],
			self::STEP_WEBSITE => ["origin_nums" => 0, "filter_nums" => 0],
			self::STEP_BIGDATA => ["origin_nums" => 0, "filter_nums" => 0],
		];
		
		if ($param)
		{
			$pushGroupLogModel = new PushGroupLog();
			$receiveData = $pushGroupLogModel->find()->where("`receive_date` = '{$param["receive_date"]}' AND `site_name` = '{$param["site_name"]}' AND `mail_type` = '{$param["mail_type"]}' ")->asArray()->all();
			if ($receiveData)
			{
				foreach ($receiveData as $key => $val)
				{
					$data[$val["step"]]["origin_nums"] = $val["origin_nums"];
					$data[$val["step"]]["filter_nums"] = $val["filter_nums"];
				}
			}
		}
		
		return $data;
	}
	
	/**
	 * 取站点类型
	 */
	protected function getSiteType($siteId = 0)
	{
		$siteType = 0;
		$webType = Yii::$app->params["sites"]["marketing_email"]["web_type"];
		foreach ($webType as $type => $val)
		{
			if (isset($val["sites"][$siteId]))
			{
				$siteType = $type;
				break;
			}
		}
		return $siteType;
	}
	
	/**
	 * 获取接口地址
	 */
	protected function getApiUrl()
	{
		$apiUrl = YII_ENV_PROD ? $this->apiConfigArr["product"]["apiUrl"] : $this->apiConfigArr["test"]["apiUrl"];
		return $apiUrl;
	}
	
	/**
	 * 获取密钥
	 */
	protected function getApiKey()
	{
		$apiKey = YII_ENV_PROD ? $this->apiConfigArr["product"]["apiKey"] : $this->apiConfigArr["test"]["apiKey"];
		return $apiKey;
	}
	
	/**
	 * 获取 类型标识
	 */
	protected function getTemplateTypeCompaign($typeId = 0)
	{
		$templateTypeCompaign = "";
		try
		{
			if ($typeId)
			{
				$sql = " SELECT template_type_compaign FROM `template_type` WHERE `id` = {$typeId} LIMIT 1";
				$data = Yii::$app->db->createCommand($sql)->queryOne();
				$templateTypeCompaign = $data ? $data["template_type_compaign"] : "";
			}
		}
		catch (\Exception $e)
		{
			echo "#FILE: " . $e->getFile() . "<br/>" . "#LINE: " . $e->getLine() . "<br/>" . "#ERROR: " . $e->getMessage();
		}
		return $templateTypeCompaign;
	}
	
	/**
	 * 统计站点各种邮件类型的今日接收量
	 */
	protected function countReceiveNum($siteInfo = [])
	{
		$data = [
			self::MAIL_TYPE_CART => 0,
			self::MAIL_TYPE_VIEW => 0
		];
		try
		{
			if ($siteInfo && isset($siteInfo["site_id"], $siteInfo["site_name"]))
			{
				$siteId = $siteInfo["site_id"];
				$siteName = $siteInfo["site_name"];
				$date = Yii::$app->systime->date("", "Y-m-d");
				//$date = "2017-11-16";
				$startTime = Yii::$app->systime->strtotime($date . " 00:00:00");  //开始时间
				$endTime = Yii::$app->systime->strtotime($date . " 23:59:59");  //结束时间
				
				//取出配置
				$sql = " SELECT is_old FROM `mail_auto_create` WHERE `site_id` = {$siteId} AND `is_del` = 0 ";
				$config = Yii::$app->db->createCommand($sql)->queryAll();
				if ($config)
				{
					$config = array_column($config, "is_old");
					foreach ($config as $isOld)
					{
						//goods_type = 1 表示购物车   goods_type = 4 表示浏览记录
						if ($isOld == 1)
						{
							$sql = " SELECT goods_type, count(1) AS total FROM `user_{$siteName}_goods_data` WHERE `create_time` BETWEEN {$startTime} AND {$endTime} GROUP BY `goods_type` ";
							$total = Yii::$app->db->createCommand($sql)->queryAll();
							if ($total)
							{
								foreach ($total as $k => $v)
								{
									if ($v["goods_type"] == 1)
									{
										$data[self::MAIL_TYPE_CART] = $v["total"];
									}
									elseif ($v["goods_type"] == 4)
									{
										$data[self::MAIL_TYPE_VIEW] = $v["total"];
									}
								}
							}
							continue;
						}
						
						//user_email_type = 1 表示购物车
						elseif ($isOld == 2)
						{
							if ($siteName == "rosegal")
							{
								//rosegal站统计的是 昨天16点至今天16点数据
								$currTime = Yii::$app->systime->time();
								$beforeTime = $currTime - 86400;  //昨天的时间戳
								$startDate = Yii::$app->systime->date($beforeTime, "Y-m-d");
								$startTime = Yii::$app->systime->strtotime($startDate . " 16:00:00");
								$endDate = Yii::$app->systime->date($currTime, "Y-m-d");
								$endTime = Yii::$app->systime->strtotime($endDate . " 16:00:00");
							}
							$sql = " SELECT user_email_type, count(1) AS total FROM `user_{$siteName}_goods_data` WHERE `create_time` BETWEEN {$startTime} AND {$endTime} GROUP BY `user_email_type` ";
							$total = Yii::$app->db->createCommand($sql)->queryAll();
							if ($total)
							{
								foreach ($total as $k => $v)
								{
									if ($v["user_email_type"] == 1)
									{
										$data[self::MAIL_TYPE_CART] = $v["total"];
									}
								}
							}
							continue;
						}
					}
				}
			}
		}
		catch (\Exception $e)
		{
			echo "#FILE: " . $e->getFile() . "<br/>" . "#LINE: " . $e->getLine() . "<br/>" . "#ERROR: " . $e->getMessage();
		}
		
		return $data;
	}
	
	/**
	 * 统计站点各种邮件类型的今日发送量
	 */
	protected function countSendNum($siteInfo = [])
	{
		$data = [
			self::MAIL_TYPE_CART => [
				"send_date" => "",
				"receive_date" => "",
				"send_nums" => 0,
			],
			self::MAIL_TYPE_VIEW => [
				"send_date" => "",
				"receive_date" => "",
				"send_nums" => 0,
			]
		];
		try
		{
			if ($siteInfo && isset($siteInfo["site_id"], $siteInfo["site_code"], $siteInfo["site_name"]))
			{
				$siteId = $siteInfo["site_id"];
				$siteCode = $siteInfo["site_code"];
				$siteName = $siteInfo["site_name"];
				$today = Yii::$app->systime->date("", "ymd");  //格式如: 171117  (2017年11月17日)
				$sendDate = Yii::$app->systime->date("", "Y-m-d");  //发送邮件的日期
				
				//取出配置
				$sql = " SELECT user_email_type, goods_type, send_mode_id, delay_day, is_old, template_id FROM `mail_auto_create` WHERE `site_id` = {$siteId} AND `is_del` = 0 AND `template_id` > 0 ";
				$config = Yii::$app->db->createCommand($sql)->queryAll();
				if ($config)
				{
					//找 mail_template 表的 type_id 字段
					$templateIdArr = array_column($config, "template_id");
					$templateIdStr = join(",", $templateIdArr);
					$sql = " SELECT template_id, type_id FROM `mail_template` WHERE `site_id` = {$siteId} AND `is_del` = 0 AND `template_id` IN({$templateIdStr}) ";
					$tempData = Yii::$app->db->createCommand($sql)->queryAll();
					$templateInfo = [];
					if ($tempData)
					{
						foreach ($tempData as $key => $val)
						{
							//找 template_type 表的 template_type_compaign 字段
							$val["template_type_compaign"] = $this->getTemplateTypeCompaign($val["type_id"]);
							$templateInfo[$val["template_id"]] = $val;
						}
					}
					
					//取数据
					foreach ($config as $key => $val)
					{
						$templateTypeCompaign = isset($templateInfo[$val["template_id"]]) ? $templateInfo[$val["template_id"]] : "";
						if (! isset($templateTypeCompaign["template_type_compaign"]) || empty($templateTypeCompaign["template_type_compaign"]))
						{
							continue;
						}
						
						//根据规则重新算 接收数据日期  send_mode_id说明: 0当天发,  1根据推送日期延后几天发, 2根据加购时间延后几天发
						$receiveDate = Yii::$app->systime->date("", "Y-m-d");  //接收数据的日期
						if ($val["send_mode_id"] == 1)
						{
							$delayDay = $val["delay_day"];
							$time = Yii::$app->systime->strtotime("-{$delayDay} day");
							$receiveDate = Yii::$app->systime->date($time, "Y-m-d");
						}
						elseif ($val["send_mode_id"] == 2)
						{
							$delayDay = $val["delay_day"];  //EMP系统设置根据加购时间,延后n天发送
							$siteDelayDay = $this->getSiteDelayDayBySiteId($siteId);  //如果站点筛选的是加购n天前的数据
							/**
							 * delayDay > siteDelayDay  则表示 delayDay - siteDelayDay 天
							 * delayDay < siteDelayDay  则取不到数据
							 * delayDay == siteDelayDay  表示当天
							 */
							if ($delayDay > $siteDelayDay)
							{
								$delayDay = $delayDay - $siteDelayDay;
								$time = Yii::$app->systime->strtotime("-{$delayDay} day");
								$receiveDate = Yii::$app->systime->date($time, "Y-m-d");
							}
							elseif ($delayDay < $siteDelayDay)
							{
								$time = Yii::$app->systime->strtotime("-{$delayDay} day");
								$receiveDate = Yii::$app->systime->date($time, "Y-m-d");
							}
							else
							{
								$receiveDate = Yii::$app->systime->date("", "Y-m-d");
							}
						}
						
						//取EMP过滤后总数
						$groupName = $siteCode . "_" . $templateTypeCompaign["template_type_compaign"] . "_" . $today . "_";
						$sql = "SELECT sum(total_count) AS total FROM `mail_group` WHERE `site_id` = {$siteId} AND `group_name` LIKE '{$groupName}%' ";  //过滤后的总数字段是 total_count, 发送成功的总数是: send_ok_count
						$total = Yii::$app->db->createCommand($sql)->queryOne();
						$total = $total ? intval($total["total"]) : 0;
						
						//组合数据
						if ($val["is_old"] == 1)
						{
							//goods_type = 1 表示购物车   goods_type = 4 表示浏览记录
							if ($val["goods_type"] == 1)
							{
								$data[self::MAIL_TYPE_CART]["receive_date"] = $receiveDate;
								$data[self::MAIL_TYPE_CART]["send_date"] = $sendDate;
								$data[self::MAIL_TYPE_CART]["send_nums"] = $total;
							}
							elseif ($val["goods_type"] == 4)
							{
								$data[self::MAIL_TYPE_VIEW]["receive_date"] = $receiveDate;
								$data[self::MAIL_TYPE_VIEW]["send_date"] = $sendDate;
								$data[self::MAIL_TYPE_VIEW]["send_nums"] = $total;
							}
						}
						elseif ($val["is_old"] == 2)
						{
							//user_email_type = 1 表示购物车
							if ($val["user_email_type"] == 1)
							{
								$data[self::MAIL_TYPE_CART]["receive_date"] = $receiveDate;
								$data[self::MAIL_TYPE_CART]["send_date"] = $sendDate;
								$data[self::MAIL_TYPE_CART]["send_nums"] = $total;
							}
						}
					}
				}
			}
		}
		catch (\Exception $e)
		{
			echo "#FILE: " . $e->getFile() . "<br/>" . "#LINE: " . $e->getLine() . "<br/>" . "#ERROR: " . $e->getMessage();
		}
		return $data;
	}
	
	/**
	 * 获取网站设置的是筛选几天前的加购数据
	 */
	protected function getSiteDelayDayBySiteId($siteId = 0)
	{
		$webDelayDay = Yii::$app->params["sites"]["marketing_email"]["web_delay_day"];
		$siteDelayDay = isset($webDelayDay[$siteId]) ? $webDelayDay[$siteId] : 0;
		return $siteDelayDay;
	}
	
	/**
	 * 创建一个并发CURL网络访问
	 *
	 * @param array $urls  要访问的地址和参数
	 *     array(
	 *         array(
	 *             "url" => "http://www.baidu.com",
	 *             "data" => array(
	 *                 "aa" => "bb"
	 *             ),
	 *             "header" => array(
	 *                 "cc" => "dd"
	 *             ),
	 *         ),
	 *         array(
	 *             "url" => "http://www.baidu.com",
	 *             "data" => array(
	 *                 "aa" => "bb"
	 *             ),
	 *             "header" => array(
	 *                 "cc" => "dd"
	 *             ),
	 *         ),
	 *     )
	 * 
	 * @return array  返回服务器的响应, false请求失败
	 */
	protected function multiRequest( $urls = array() )
	{
		if( !is_array( $urls ) || empty( $urls ) )
		{
			return false;
		}
		
		$queue = curl_multi_init();
		$map = array();
		$ret = array();

		$i = 0;
		foreach ($urls as $uriKey => $data)
		{
			if( is_string( $data ) )
			{
				$url = $data;
				$post = array();
				$header = array();
			}
			else
			{
				$url = empty( $data["url"] ) ? "" : trim( $data["url"] );
				$post = empty( $data["data"] ) ? array() : $data["data"];
				$header = empty( $data["header"] ) ? array() : $data["header"];
			}
			if( empty( $url ) )
			{
				return false;
			}
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // 5秒超时
			//curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 10秒超时
			if( $header )
			{
				$temp = array();
				foreach( $header as $key => $val )
					$temp[] = "{$key}: {$val}";
				curl_setopt ( $ch, CURLOPT_HTTPHEADER, $temp );
			}
			if( $post )
			{
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
			}
			curl_multi_add_handle($queue, $ch);
			$map[(string) $ch] = $uriKey;
			$i ++;
		}

		$responses = array();
		do
		{
			while ( ($code = curl_multi_exec($queue, $active) ) == CURLM_CALL_MULTI_PERFORM ) ;
			if ($code != CURLM_OK)
			{
				break;
			}
			// a request was just completed -- find out which one
			while ($done = curl_multi_info_read($queue))
			{
				// get the info and content returned on the request
				//$info = curl_getinfo($done['handle']);
				//$error = curl_error($done['handle']);
				$output = curl_multi_getcontent($done['handle']);
				$startVar = substr( $output, 0, 1 );
				$endVar = substr( $output, strlen($output) - 1, 1 );
				if( $startVar == '{' && $endVar == '}' || $startVar == '[' && $endVar == ']' )
				{
					$temp = @json_decode( $output, true );
					if( $temp !== false )
						$output = $temp;
				}
				$ret[$map[(string) $done['handle']]] = $output;
				//$results = callback(curl_multi_getcontent($done['handle']), $delay);
				//$responses[$map[(string) $done['handle']]] = compact('info', 'error', 'results');
				// remove the curl handle that just completed
				curl_multi_remove_handle($queue, $done['handle']);
				curl_close($done['handle']);
			}

			// Block for data in / output; error handling is done by curl_multi_exec
			if ($active > 0)
			{
				curl_multi_select($queue, 0.5);
			}
		}
		while ($active);

		curl_multi_close($queue);
		return $ret;
	}
}